#pragma once
#include "Thread.hpp"
#include "Log.hpp"
#include <iostream>
#include <vector>
#include <queue>
#include <pthread.h>
#include "LockGuard.hpp"

using namespace ThreadModule;

const int gdefaultthreadnum = 3;
template <typename T>
class ThreadPool
{
private:
    void LockQueue()
    {
        pthread_mutex_lock(&_mutex);
    }
    void UnLockQueue()
    {
        pthread_mutex_unlock(&_mutex);
    }
    void ThreadSleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }
    void ThreadWakeup()
    {
        pthread_cond_signal(&_cond);
    }
    void WekeUpThreadAll()
    {
        pthread_cond_broadcast(&_cond);
    }
    ThreadPool(int threadnum = gdefaultthreadnum) : _threadnum(threadnum), _waitthread(0), _isrunning(false)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
        // 构造后记录日志
        LOG(INFO, "ThreadPool Construct()\n");
    }

    // 启动线程
    void Start()
    {
        for (auto &thread : _threads)
        {
            thread.Start();
        }
    }
    void HandlerTask(std::string &name)
    {
        LOG(INFO, "%s is runing...\n", name.c_str());
        while (true)
        {
            // 1. 保证数据的安全
            LockQueue();
            // 2. 队列中不一定有任务
            // 如果队列为空 && 线程池是启动的，就进人等待装态
            while (_task_queue.empty() && _isrunning)
            {
                _waitthread++;
                ThreadSleep();
                _waitthread--;
            }

            // 如果队列为空了 && 线程池关闭了，直接退出
            if (_task_queue.empty() && !_isrunning)
            {
                UnLockQueue();
                // std::cout << name << " quit..." << std::endl;
                break;
            }

            // 如果队列不为空, 不管线程池有没有退出都要完成任务
            //  3. 有任务，取出任务
            T t = _task_queue.front();
            _task_queue.pop();
            UnLockQueue();

            // 获取任务记录日志
            LOG(DEBUG, "%s get a task...\n", name.c_str());
            // 4. 处理任务，这个任务属于线程独占的任务，不能放在加锁和解锁之间
            t();

            // 处理任务记录日志
            // LOG(DEBUG, "%s hander a task, result is : %s", name.c_str(), t.ResultTostring().c_str());
        }
    }
    // 创建线程
    void InitThreadPool()
    {
        for (int num = 0; num < _threadnum; num++)
        {
            std::string name = "thread-" + std::to_string(num + 1);
            // _threads.emplace_back(Print, name);
            // 用bind可以解决类当中，一个类把自己的成员方法想设置成另一个类的回调方法，常见的方法就是使用bind
            // 可以方便我们进行类级别的互相调用
            _threads.emplace_back(std::bind(&ThreadPool::HandlerTask, this, std::placeholders::_1), name);

            // 初始化后记录日志
            LOG(INFO, "init thread %s done\n", name.c_str());
        }
        _isrunning = true;
    }
    ThreadPool<T> &operator=(const ThreadPool<T> &) = delete;
    ThreadPool(const ThreadPool<T> &) = delete;

public:
    static ThreadPool<T> *GetINstance()
    {
        if (nullptr == _instance) // 保证第二次，所有线程都不用加锁，直接返回_instance单例对象
        {
            LockGuard lock(&_lock);
            if (nullptr == _instance)
            {
                _instance = new ThreadPool<T>();
                _instance->InitThreadPool();
                _instance->Start();
                LOG(DEBUG, "创建线程池单例成功\n");
                return _instance;
            }
            else
            {
                LOG(DEBUG, "获取线程池单例成功\n");
            }
        }
        else
        {
            LOG(DEBUG, "获取线程池单例成功\n");
        }

        return _instance;
    }

    void Stop()
    {
        LockQueue();
        // 这个是在临界区使用的，要进行保护
        _isrunning = false;
        WekeUpThreadAll();
        UnLockQueue();
    }
    void WaitAll()
    {
        for (auto &thread : _threads)
        {
            thread.Join();

            // 线程退出记录日志
            LOG(INFO, "%s is quit...\n", thread.name().c_str());
        }
    }
    bool Enqueue(const T &t)
    {
        bool ret = false;
        // 1. 保证数据的安全
        LockQueue();
        if (_isrunning)
        {
            _task_queue.push(t);
            if (_waitthread > 0)
            {
                ThreadWakeup();
            }

            // 任务入队列记录日志
            LOG(DEBUG, "enqueue task success...\n");
            ret = true;
        }
        UnLockQueue();
        return ret;
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

private:
    int _threadnum; // 线程的个数
    std::vector<Thread> _threads;
    std::queue<T> _task_queue;
    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    int _waitthread;
    bool _isrunning;

    // 添加单例模式
    static ThreadPool<T> *_instance;
    // 可能会有多个线程同时申请单例，需要加锁保护
    static pthread_mutex_t _lock;
};

template <typename T>
ThreadPool<T> *ThreadPool<T>::_instance = nullptr;

template <typename T>
pthread_mutex_t ThreadPool<T>::_lock = PTHREAD_MUTEX_INITIALIZER;